package org.scohen.juploadr.uploadapi.zooomr.photosets;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.scohen.juploadr.app.PhotoSet;
import org.scohen.juploadr.uploadapi.zooomr.DefaultZooomrHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

public class GetPhotosetListHandler extends DefaultZooomrHandler {
    private ZooomrPhotoSet photoSet;
    private List<PhotoSet> photoSets;

    public GetPhotosetListHandler(Object parent) {
        super(parent);
        photoSets = new ArrayList<PhotoSet>();

    }

    public void startElement(String uri, String localName, String qname,
            Attributes atts) throws SAXException {
        super.startElement(uri, localName, qname, atts);
        if ("photoset".equals(qname)) {
            if (photoSet != null) {
                photoSets.add(photoSet);
            }
            photoSet = new ZooomrPhotoSet();
            photoSet.setId(atts.getValue("id"));
            photoSet.setPrimaryPhotoId(atts.getValue("primary"));
            photoSet.setNumberOfPhotos(Integer
                    .parseInt(atts.getValue("photos")));
            photoSet.setSecret(atts.getValue("secret"));
            photoSet.setServer(atts.getValue("server"));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
     */
    public void characters(char[] chars, int start, int end)
            throws SAXException {
        super.characters(chars, start, end);
        String cdata = new String(chars, start, end).trim();

        if (cdata.length() > 0) {
            if ("title".equals(lastTag)) {
                photoSet.setTitle(cdata);
            } else if ("description".equals(lastTag)) {
                photoSet.setDescription(cdata);
            }
        }
    }

    public void endDocument() throws SAXException {
        if (photoSet != null) {
            photoSets.add(photoSet);
        }
    }

    public List<PhotoSet> getPhotoSets() {
        ZooomrPhotoSet ps = new ZooomrPhotoSet();
        Collections.sort(photoSets, ps.new TitleComparator());
        return photoSets;
    }

}
